<template>
    <div class="container">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input placeholder="跟单编号" v-model="searchForm.followOrderNumber" style="width: 150px; margin-right: 10px"></el-input>
        <el-input placeholder="单据编码" v-model="searchForm.documentCode" style="width: 150px; margin-right: 10px"></el-input>
        <el-input placeholder="物料编码" v-model="searchForm.materialCode" style="width: 150px; margin-right: 10px"></el-input>
        <el-input placeholder="物料名称" v-model="searchForm.materialName" style="width: 150px; margin-right: 10px"></el-input>
        <el-date-picker
          v-model="searchForm.startDate"
          type="date"
          placeholder="开始日期"
          style="width: 150px; margin-right: 10px"
        ></el-date-picker>
        <el-date-picker
          v-model="searchForm.endDate"
          type="date"
          placeholder="结束日期"
          style="width: 150px; margin-right: 10px"
        ></el-date-picker>
        <el-button type="primary" @click="searchData">搜索</el-button>
      </div>
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="toggleTable">
          {{ showBillTable ? '明细' : '单据' }}
        </el-button>
        <el-button type="primary" @click="queryAll">查询所有</el-button>
        <el-button type="success" @click="addNew">新增</el-button>
        <el-button type="danger" @click="DeleteAll(selectedIds)">删除</el-button>
        <el-button type="warning" @click="batchExport(selectedIds)">导出</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" border fit  @selection-change="handleSelectionChange">
        <template v-if="showBillTable">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="单据编码" prop="documentCode"></el-table-column>
          <el-table-column label="单据日期" prop="documentDate">
            <template #default="scope">
              {{ formatDate(scope.row.documentDate) }}
            </template>
          </el-table-column>
          <el-table-column label="单据状态" prop="documentStatus">
            <template #default="scope">
              <span :style="{color: scope.row.documentStatus === '开立' ? 'orange' : 'green'}">{{ scope.row.documentStatus }}</span>
            </template>
          </el-table-column>
          <el-table-column label="业务类型" prop="businessType"></el-table-column>
          <el-table-column label="业务状态" prop="businessStatus"></el-table-column>
          <el-table-column label="审核日期" prop="auditDate">
            <template #default="scope">
              {{ formatAuditDate(scope.row.auditDate) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button link type="primary" @click="viewDetail(scope.row)">查看</el-button>
              <el-button link type="success" @click="updatedata(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="deleteData(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column label="跟单编号" prop="followOrderNumber"></el-table-column>
          <el-table-column label="订单交期" prop="orderDeliveryDate">
            <template #default="scope">
              {{"2025-05-18"}}
            </template>
          </el-table-column>
          <el-table-column label="单据编码" prop="documentCode"></el-table-column>
          <el-table-column label="单据状态" prop="documentStatus"></el-table-column>
          <el-table-column label="仓库" prop="warehouse"></el-table-column>
          <el-table-column label="计划单号" prop="planOrderNumber"></el-table-column>
          <el-table-column label="供应商" prop="supplier"></el-table-column>
          <el-table-column label="物料名称" prop="materialName"></el-table-column>
          <el-table-column label="物料编码" prop="materialCode"></el-table-column>
          <el-table-column label="到货数量" prop="arrivalQuantity"></el-table-column>
          <el-table-column label="入库数量" prop="inStockQuantity"></el-table-column>
          <el-table-column label="单据日期" prop="documentDate">
            <template #default="scope">
              {{ formatDate(scope.row.documentDate) }}
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
</template>

<script setup>
import { ref, reactive,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage,ElMessageBox} from 'element-plus';
import { KongaUrl } from '@/axios/axiosHelp';
const router = useRouter();

// 格式化日期函数
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 格式化审核日期，1900-1-1不显示
const formatAuditDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  if (d.getFullYear() === 1900 && d.getMonth() === 0 && d.getDate() === 1) return '';
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

onMounted(()=>{
  queryAll();
})
const selectedIds=ref([]);
// 搜索表单数据
const searchForm = reactive({
  followOrderNumber: '',
  documentCode: '',
  materialCode: '',
  materialName: '',
  startDate: '',
  endDate: '',
  pageindex:1,
  pagesize:15
});

// 表格数据
const tableData = ref([]);

// 搜索方法
const searchData = () => {
  // 这里可以编写调用后端接口进行搜索的逻辑，目前仅模拟清空表格数据
  tableData.value = [];
  console.log('搜索条件', searchForm);
};
const page=ref([])
const deleteData=(id)=>{
  page.value=id;
  console.log(page.value);
  ElMessageBox.confirm('确定删除该数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => {
    KongaUrl({
      url:'/weiwaixie/api/Outsour/DeleteOutArrvalID',
      method:'post',
      data:{
        id:id
      }
  })
  .then(res=>{
    if(res.data.code==101){
      ElMessage.success("操作成功");
      queryAll();
    }
  })})
  .catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 查询所有方法
const queryAll = () => {
  KongaUrl({
    url:'/weiwaidu/api/OutSourc/QuertOutArrial',
    method:'get',
    params:{
      DocumentCode:searchForm.documentCode,
      MaterialCode:searchForm.materialCode,
      MaterialName:searchForm.materialName,
      StartDate:searchForm.startDate,
      EndDate:searchForm.endDate,
      pageindex:searchForm.pageindex,
      pagesize:searchForm.pagesize
    }
  })
  .then(res=>{
    if(res.data.code==101){
      tableData.value=res.data.list;
    }
    console.log(res);
  })
};

// 新增方法
const addNew = () => {
  console.log('执行新增操作');
  router.push('/AddOutsourceddelivery');
};

//导出
const batchExport = async () => {
    // 判断 selectedIds 的长度是否为 0
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请选择要导出的数据');
        return;
    }

    try {
        const res = await KongaUrl.get('/weowaodu/api/OutSourc/Daochudaohuo', {
            params: {
                // 将参数名改为 Id，与后端保持一致
                Id: selectedIds.value
            },
            paramsSerializer: (params) => {
                const parts = [];
                for (const key in params) {
                    if (Array.isArray(params[key])) {
                        params[key].forEach((value) => {
                            parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
                        });
                    } else {
                        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
                    }
                }
                return parts.join('&');
            },
            responseType: 'blob'
        });
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, '委外到货单列表.xlsx');
    } catch (error) {
        ElMessage.error('批量导出失败，请联系管理员');
        console.error('批量导出错误:', error);
    }
};    

const showBillTable = ref(false);
const toggleTable = () => {
  showBillTable.value = !showBillTable.value;
};

const viewDetail = (row) => {
  router.push({
    path: '/daohuoxiangqing',
    query: { ...row }
  });
};
// 选择项变化
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
  console.log('选中的数据', selectedIds.value)
}
// 批量删除操作
const DeleteAll = (id) => {
  console.log('选中批量的数据', id.length)
  console.log('选中的数据', id)
  
  if(id.length === 0){
    ElMessage.error("请选择数据")
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${id.length} 条数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 修正后的请求方式
      const response = await KongaUrl({
        url: '/weiwaixie/api/Outsour/DeleteOutArrval',
        method: 'post',
        data:{
          Id:id
        }
      })
      
      if(response.data.code == 101) {
        ElMessage.success('删除成功')
        // 刷新数据
        queryAll();
      } 
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}
//编辑
const updatedata=(row)=>{
  router.push({
    path:'/UpdateOutSoureddelivery',
    query:{...row}
  })
}
</script>

<style scoped>
.container {
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
}
.search-bar {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.search-bar .el-input,
.search-bar .el-date-picker {
  flex: 1;
  min-width: 150px;
  max-width: 200px;
}
.action-buttons {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
}
.el-table {
  width: 100% !important;
  margin-top: 10px;
  table-layout: fixed;
}
.el-table-column {
  min-width: 80px;
}
</style>